<?php

namespace app\admin\model\ldcms;

use addons\ldcms\model\common\Backend;
use Symfony\Component\VarExporter\VarExporter;
use think\Cache;
use think\Db;
use think\Exception;
use think\Lang;
use think\Model;


class Langs extends Backend
{
    // 表名
    protected $name = 'ldcms_langs';
    protected static $langpath=ADDON_PATH.'ldcms'.DS.'lang'.DS;
    protected static $siteinfopath=ADDON_PATH.'ldcms'.DS.'data'.DS.'site_info'.DS;

    // 追加属性
    protected $append = [
        'create_time_text',
        'update_time_text'
    ];

    public static function init(){
        self::afterInsert(function ($data){
            self::createLangFile(self::$langpath.$data['code'].'.php',self::$langpath.'zh-cn.php');
            self::createLangFile(self::$siteinfopath.$data['code'].'.php',self::$siteinfopath.'zh-cn.php');
        });

        self::beforeUpdate(function ($data){
            $old_data=Db::name('ldcms_langs')->where('id',$data['id'])->find();
            if($old_data['code']!=$data['code']){
                rename(self::$langpath.$old_data['code'].'.php',self::$langpath.$data['code'].'.php');
                rename(self::$siteinfopath.$old_data['code'].'.php',self::$siteinfopath.$data['code'].'.php');
            }
        });

        self::beforeDelete(function ($data){
           if($data['code']==get_lang()){
               throw new Exception('当前语言被选中不能删除');
           }
        });

        self::afterDelete(function ($data){
            @unlink(self::$langpath.$data['code'].'.php');
            @unlink(self::$siteinfopath.$data['code'].'.php');
            set_lang('backend_language',config('default_lang'));
        });
        Cache::clear('ldcmslang');
    }

    /*创建语言文件*/
    protected static function createLangFile($carate_path,$copy_path){
        $data=require $copy_path;
        // 写入lang文件
        $res = file_put_contents($carate_path, "<?php\n\n" . "return " . VarExporter::export($data) . ";\n", LOCK_EX);
        if (!$res) {
            throw new Exception('文件写入失败 请确定'.$carate_path.'目录有写入权限');
        }
    }

    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['update_time']) ? $data['update_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
}
